package cn.exempale.mscapplication.ui;


import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import java.util.List;

import cn.exempale.mscapplication.R;
import cn.exempale.mscapplication.databinding.ActivityResultBinding;
import cn.exempale.mscapplication.dto.TaskDTO;
import cn.exempale.mscapplication.emnus.StatusType;
import cn.exempale.mscapplication.model.db.entity.ResultEntity;
import cn.exempale.mscapplication.model.db.entity.TaskEntity;
import cn.exempale.mscapplication.model.net.callback.Resource;
import cn.exempale.mscapplication.viewModel.ResultViewModel;
import cn.exempale.mscapplication.vo.ResultVO;

public class ResultActivity extends BaseActivity {

    private ResultViewModel viewModel;
    private ActivityResultBinding binding;
    private TaskEntity taskEntity;
    private ResultAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_result);
        binding.setLifecycleOwner(this);
        viewModel = new ViewModelProvider(this).get(ResultViewModel.class);
        Intent intent = getIntent();
        taskEntity = (TaskEntity) intent.getSerializableExtra("task");
        binding.setTask(taskEntity);
        adapter = new ResultAdapter(this);
        binding.resultRecyclerView.setAdapter(adapter);
        // 获取结果数据
        resultDAO.findByTaskId(taskEntity.getTaskId()).observe(this, resultEntities -> {
            if (resultEntities == null || resultEntities.size() == 0) {
                executor.execute(() -> {
                    // 数据库没结果，同步服务器数据
                    TaskDTO dto = new TaskDTO();
                    dto.setTask_id(taskEntity.getTaskId());
                    Resource<List<ResultVO>> resource = viewModel.getResult(dto);
                    if (resource.status == StatusType.ERROR) {
                        // 失败
                        Toast.makeText(getBaseContext(), resource.msg, Toast.LENGTH_SHORT).show();
                    } else if (resource.status == StatusType.SUCCESS) {
                        // 成功
                        resultDAO.findByTaskId(taskEntity.getTaskId());
                    }
                });
            } else {
                // 数据库中有结果直接显示
                if (resultEntities.size() >= 2) {
                    adapter.setContact1(resultEntities.get(0).getSpeaker());
                    adapter.setContact2(resultEntities.get(1).getSpeaker());
                } else if (resultEntities.size() >= 1) {
                    adapter.setContact1(resultEntities.get(0).getSpeaker());
                }
                adapter.setResults(resultEntities);
            }
        });
    }
}